package NIOTest;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * @author zyc
 * @create 2022--05--31 20:52
 */
public class NIOServer {
    public static void main(String[] args) throws IOException {
        //获取服务端通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //获取选择器
        Selector selector = Selector.open();
        //服务端监听一个端口
        serverSocketChannel.socket().bind(new InetSocketAddress(5555));
        //非阻塞
        serverSocketChannel.configureBlocking(false);
        //
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            if (selector.select(5000) == 0) {
                System.out.println("服务器等待了5秒没有连接");
                continue;
            }

            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                //若当前key是一个新连接
                if (key.isAcceptable()) {
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    System.out.println("客户端连接成功" + socketChannel.hashCode());
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));

                }
                //若当前key准备就绪了
                if (key.isReadable()) {
                    SocketChannel channel = (SocketChannel) key.channel();

                    ByteBuffer byteBuffer = (ByteBuffer) key.attachment();

                    channel.read(byteBuffer);
                    System.out.println("来着客户端的数据：" + new String(byteBuffer.array()));
                }
                //防止其他线程重复运行
                iterator.remove();
            }
        }
    }
}
